const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const cors = require('cors');
const axios = require('axios')
const server = require('http').createServer(app);
const io = require('socket.io')(server, {
  cors: {
    origin: "*"
  }
});
const automaticReply = new Map();
const OSS = require('ali-oss');
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();

const store = new OSS({
  region: 'oss-cn-beijing',
  accessKeyId: 'LTAI5tPrTpBE7LhdeE9vXMLm',
  accessKeySecret: 'kZTuoqygmGvKZ3nkg1YpvSogrBjErx',
  bucket: 'qkofnolewndwolmdwlq',
});

app.use(cors());
app.use(express.json())

io.on('connection', (socket) => {
  socket.on('update', (data) => {
    if (!data) {
      io.emit('update', data);;
      return
    }
    console.log(data)
    console.log('------------------------')
    console.log(automaticReply)
    console.log(automaticReply.has(data.doctorId))
    if (automaticReply.has(data.doctorId)) {
      const item = automaticReply.get(data.doctorId)
      const putData = {
        content: item.content,
        inquiryId: data.inquiryId,
        type: '1',
        userId: data.userId
      }
      // formData.append('content', item.content)
      // formData.append('inquiryId', data.inquiryId)
      // formData.append('type', "1")
      // formData.append('userId', data.userId)

      axios({
        method: 'post',
        url: 'http://10.59.9.18/health/doctor/inquiry/verify/v1/pushMessage',
        data: putData,
        headers: {
          doctorId: data.doctorId,
          sessionId: item.sessionId,

          "Content-Type": "application/x-www-form-urlencoded"
        }
      }).then(() => {
        io.emit('update', data);
      })

    } else {
      io.emit('update', data);
    }

  });
});

// 自动回复
app.post('/auto/reply', (req, res) => {
  const {
    doctorId,
    content,
    sessionId
  } = req.body;
  automaticReply.set(doctorId.toString(), {
    doctorId,
    content,
    sessionId
  })
  res.send({
    status: '0000',
    message: '设置成功'
  })
})

// 删除自动回复
app.delete('/auto/reply/:doctorId', (req, res) => {
  const {
    doctorId
  } = req.params;
  automaticReply.delete(doctorId)
  res.send({
    status: '0000',
    message: '取消自动回复'
  })
})

// 获取自动回复
app.get('/auto/reply/:doctorId', (req, res) => {
  const {
    doctorId
  } = req.params;

  res.send({
    status: '0000',
    message: '获取成功',
    result: automaticReply.get(doctorId)
  })
})

app.post('/chat/login', async (req, res) => {
  const {
    loginId,
    loginPwd
  } = req.body;

  const resp = await axios.post('https://study.duyiedu.com/api/user/login', {
    loginId,
    loginPwd
  })
  const {
    code
  } = resp.data;
  if (code === 400) {
    const existData = await axios.get('https://study.duyiedu.com/api/user/exists?loginId=' + loginId);
    console.log(existData.data)
    if (existData.data.data) {
      res.send({
        status: '4000',
        message: '账号存在， 密码错误'
      })
    } else {
      const registData = await axios.post('https://study.duyiedu.com/api/user/reg', {
        loginId,
        loginPwd,
        'nickname': 'wdyl'
      });
      if (registData.data.code === 0) {
        const resp = await axios.post('https://study.duyiedu.com/api/user/login', {
          loginId,
          loginPwd
        })
        res.setHeader('token', resp.headers.authorization)
        res.send({
          "status": '0000',
          message: '注册成功'
        })
      } else {
        res.send({
          "status": '4000',
          message: registData.data.message
        })
      }
    }
  } else {
    res.setHeader('token', resp.headers.authorization)
    res.send({
      "status": '0000',
      message: '登录成功'
    })
  }
})

app.get('/chat/robot', async (req, res) => {
  const resp = await axios({
    method: 'post',
    url: 'https://study.duyiedu.com/api/chat',
    data: {
      content: req.query.content
    },
    headers: {
      authorization: `Bearer ${req.headers.token}`
    }
  })

  res.send({
    status: '0000',
    message: '获取成功',
    result: resp.data.data.content
  })
})

app.get('/chat/history', async (req, res) => {
  const resp = await axios({
    method: 'get',
    url: 'https://study.duyiedu.com/api/chat/history',
    headers: {
      authorization: `Bearer ${req.headers.token}`
    }
  })

  res.send({
    status: '0000',
    message: '获取成功',
    result: resp.data.data
  })
})

app.post('/upload', multipartMiddleware, async (req, res) => {
  const {
    originalFilename,
    path,
    type
  } = req.files.file
  const result = await store.put(originalFilename, path)
  res.send({
    data: result,
    type: type
  })
})

server.listen(8000, () => {
  console.log('listening on *:8000');
});